import {
    View, ScrollView, Dimensions, Picker, TouchableOpacity, DeviceEventEmitter,
    Text, StyleSheet, Image, Alert, DatePickerAndroid, TimePickerAndroid, TextInput
} from 'react-native';
import React, {Component} from 'react';
import Urls, {getRealUrl} from '../const/Urls'
import LocalImg from '../const/Images'
import moment from 'moment'
import {Button, TextareaItem, Toast} from 'antd-mobile-rn'


const {width, height} = Dimensions.get("window");

class PageQzdlrDetail extends Component {

    constructor(props) {
        super(props);
        this.data = this.props.navigation.getParam('data');
        this.id = this.props.navigation.getParam('id');
        let d = new Date();
        this.state = {
            startDate: d,
            startHour: d.getHours(),
            startMinute: d.getMinutes(),
            total: 0,
            times: 0,
            endDate: d,
            endHour: d.getHours(),
            endMinute: d.getMinutes(),
            shapeState: this.data.app_purpose,
            city: [],
            from: '',
            to: '',
            note: '',
            line_type: this.data.line_type,
            tuopower: ''
        };
    }

    componentDidMount() {
        this.loadData();
    }

    loadData() {
        fetch(Urls['locationUrl'], {
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json"
                },
            }
        )
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson instanceof Array) {
                    responseJson = responseJson.filter(s => s.dmh != "");
                    let ret = [];
                    responseJson.forEach(s => ret.push({label: s.dmnr, value: s.dmh}));

                    let from = ret.filter(s =>
                        s.value === this.data.pilot_place_from_id)[0];
                    let to = ret.filter(s =>
                        s.value === this.data.pilot_place_to_id)[0];

                    this.setState({
                        city: ret,
                        from: from.value,
                        to: to.value
                    });

                }
            })
            .catch(error => {
                console.error(error);
            });
    }


    processDateTime(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('DD/HHmm')
        } else
            return ""
    }

    render() {
        return (
            <View style={{
                width: width,
                height: height,
                flexDirection: 'column',
                backgroundColor: '#ffffff',
                paddingBottom: 20
            }}>
                {this.renderHeader()}
                {this.renderBody()}
            </View>


        )
    }


    renderHeader() {

        return (<View style={{
            flexDirection: 'row',
            flex: 0,
            height: 60,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#0066FF'
        }}>
            <View style={{flex: 1, padding: 10}}>
                <TouchableOpacity onPress={() => this.props.navigation.pop()}>
                    <Image source={LocalImg['backImg']}
                           style={{height: 30, width: 30, resizeMode: 'contain'}}/>
                </TouchableOpacity>
            </View>
            <View style={{flex: 3, justifyContent: 'center', alignItems: 'center'}}>
                <Text style={{fontSize: 20, color: '#ffffff'}}>
                    {this.data.ship_name}
                </Text>
            </View>
            <View style={{flex: 1, padding: 10}}>
            </View>
        </View>)
    }


    renderBody() {

        return (
            <ScrollView style={{backgroundColor: '#fffff0', height: height - 80}}>
                <View style={styles.card}>
                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>船名</Text>
                            <Text style={styles.textContent}>{this.data.ship_name}</Text>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>代理公司</Text>
                            <Text style={styles.textContent}>{this.data.agent_name}</Text>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>船公司</Text>
                            <Text style={styles.textContent}>{this.data.ship_owner}</Text>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>总吨位</Text>
                            <Text style={styles.textContent}>{this.data.ship_zdw}</Text>
                        </View>

                        <View style={styles.cell}>
                            <Text style={styles.text}>净吨位</Text>
                            <Text style={styles.textContent}>{this.data.ship_jdw}</Text>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>长度</Text>
                            <Text style={styles.textContent}>{this.data.ship_length}</Text>
                        </View>
                        <View style={styles.cell}>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>前吃水</Text>
                            <Text style={styles.textContent}>{this.data.c_csq}</Text>
                        </View>

                        <View style={styles.cell}>
                            <Text style={styles.text}>后吃水</Text>
                            <Text style={styles.textContent}>{this.data.c_csh}</Text>
                        </View>
                    </View>


                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>引航员</Text>
                            <Text style={styles.textContent}>{this.getPilot()}</Text>
                        </View>
                    </View>


                </View>

                <View style={styles.card}>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>状态</Text>

                            <View style={{flex: 1}}>
                                <Picker
                                    style={{
                                        flex: 1,
                                        marginLeft: -6,
                                        height: 28
                                    }}
                                    mode={Picker.MODE_DIALOG}
                                    selectedValue={this.state.shapeState}
                                    onValueChange={choice => this.setState({shapeState: choice})}>

                                    <Picker.Item key={0} label="进港" value={'1'}/>
                                    <Picker.Item key={1} label="出港" value={'2'}/>
                                    <Picker.Item key={2} label="移泊" value={'3'}/>
                                    <Picker.Item key={3} label="海上引航" value={'4'}/>
                                    <Picker.Item key={4} label="其他" value={'5'}/>
                                </Picker>
                            </View>


                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>航线范围</Text>
                            <View style={{flex: 1}}>
                                <Picker
                                    style={{
                                        flex: 1,
                                        marginLeft: -6,
                                        height: 28
                                    }}
                                    mode={Picker.MODE_DIALOG}
                                    selectedValue={this.data.line_type}
                                    onValueChange={text => this.setState({line_type: text})}>

                                    <Picker.Item label="国际" value={'0'}/>
                                    <Picker.Item label="国内" value={'1'}/>

                                </Picker>
                            </View>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <View style={{flex: 1, justifyContent: 'center'}}>
                                <Text>拖轮功率</Text>
                            </View>
                            <View style={{flex: 1}}>
                                <TextInput
                                    style={{
                                        flex: 1, height: 28,
                                        padding: 0,
                                    }}
                                    placeholder='请输入'
                                    onChangeText={(text) => this.setState({tuopower: text})}
                                    value={this.state.tuopower}
                                />
                            </View>
                        </View>
                    </View>

                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <View style={{flex: 1, justifyContent: 'center'}}>
                                <Text>地点自</Text>
                            </View>
                            <View style={{flex: 1}}>
                                <Picker
                                    style={{
                                        flex: 1,
                                        marginLeft: -6,
                                        height: 28,
                                        width: 1200
                                    }}
                                    mode={Picker.MODE_DIALOG}
                                    selectedValue={this.state.from}
                                    onValueChange={choice => this.setState({from: choice})}>
                                    {this.state.city.map((info, index) => {
                                        return (
                                            <Picker.Item key={info.value} label={info.label}
                                                         value={info.value}/>
                                        );
                                    })}
                                </Picker>
                            </View>
                        </View>
                    </View>


                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <View style={{flex: 1, justifyContent: 'center'}}>
                                <Text>至</Text>
                            </View>
                            <View style={{flex: 1}}>
                                <Picker
                                    style={{
                                        flex: 1,
                                        marginLeft: -6,
                                        height: 28,
                                        width: 1200
                                    }}
                                    mode={Picker.MODE_DIALOG}
                                    selectedValue={this.state.to}
                                    onValueChange={choice => this.setState({to: choice})}>
                                    {this.state.city.map((info, index) => {
                                        return (
                                            <Picker.Item key={info.value} label={info.label}
                                                         value={info.value}/>
                                        );
                                    })}
                                </Picker>
                            </View>
                        </View>
                    </View>


                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>引航员登船时间</Text>

                            <View style={{
                                flex: 1,
                                justifyContent: 'center',
                                alignItems: 'center',
                                flexDirection: 'row',
                                borderBottomWidth: 1,
                                borderColor: '#000000',
                            }}>

                                <TouchableOpacity onPress={() => this.selectStartDate()}>

                                    <Text style={{
                                        textAlign: 'center',
                                    }}>{this.getFormatDate(this.state.startDate)}</Text>

                                </TouchableOpacity>

                                <TouchableOpacity onPress={() => this.selectStartTime()}>

                                    <Text style={{
                                        marginLeft: 10,
                                        textAlign: 'center',
                                    }}>{this.getFormatTime(this.state.startHour, this.state.startMinute)}</Text>
                                </TouchableOpacity>
                            </View>

                        </View>
                    </View>
                    <View style={styles.row}>
                        <View style={styles.cell}>
                            <Text style={styles.text}>引航员工作完成时间</Text>
                            <View style={{
                                flex: 1,
                                justifyContent: 'center',
                                alignItems: 'center',
                                flexDirection: 'row',
                                borderBottomWidth: 1,
                                borderColor: '#000000',
                            }}>

                                <TouchableOpacity onPress={() => this.selectEndDate()}>

                                    <Text style={{
                                        textAlign: 'center',
                                    }}>{this.getFormatDate(this.state.endDate)}</Text>

                                </TouchableOpacity>


                                <TouchableOpacity onPress={() => this.selectEndTime()}>

                                    <Text style={{
                                        marginLeft: 10,
                                        textAlign: 'center',
                                    }}>{this.getFormatTime(this.state.endHour, this.state.endMinute)}</Text>
                                </TouchableOpacity>
                            </View>

                        </View>
                    </View>

                    <View style={{
                        flex: 1, marginLeft: 4,
                        marginRight: 4, padding: 10
                    }}>
                        <View style={{flexDirection: 'column', width: '100%'}}>
                            <TextareaItem
                                placeholder="备注"
                                value={this.state.note}
                                onChange={(value) => this.setState({note: value})}
                                style={{
                                    fontSize: 14, width: '100%',
                                    borderWidth: 1, height: 80,
                                    borderColor: '#CCCCCC', borderStyle: 'solid'
                                }}/>
                        </View>
                    </View>
                </View>


                <View style={{flexDirection: 'row', justifyContent: 'space-between', marginTop: 20, marginBottom: 20}}>
                    <Button style={{marginLeft: 40}} onClick={() => this.props.navigation.pop()}>取消</Button>
                    <Button style={{marginRight: 40}} onClick={() => this.save()}>保存</Button>
                </View>

            </ScrollView>
        )

    }

    save() {
        const request = {};
        request['PILOT_SHIFT_FROM_ID'] = this.state.from;
        request['PILOT_SHIFT_TO_ID'] = this.state.to;
        request['app_purpose'] = this.state.shapeState;
        request['PLAN_ID'] = this.data.idh;
        request['INPUTER_ID'] = this.id;
        request['pilot_embark_time'] = this.getFormatDate(this.state.startDate) + " " +
            this.getFormatTime(this.state.startHour, this.state.startMinute);
        request['pilot_disembark_time'] = this.getFormatDate(this.state.endDate) + " " +
            this.getFormatTime(this.state.endHour, this.state.endMinute);
        request['NODE'] = this.state.note;
        request['LINE_TYPE'] = this.state.line_type;
        request['TUOPOWER'] = this.state.tuopower;


        fetch(Urls['qzdlrUrl'], {
            method: "POST",
            body: JSON.stringify(request),
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
        })
            .then(response => response.json())
            .then(responseJson => {
                if (responseJson['result']) {
                    DeviceEventEmitter.emit('commit');
                    Toast.success("填写成功！");
                    this.props.navigation.pop();
                } else {
                    Toast.fail(JSON.stringify(responseJson));
                }
            })
            .catch(error => {
                console.error(error);
            });

    }

    onChange(value) {
        this.setState({
                from: value
            }
        )
    }

    onEndChange(value) {
        this.setState({
                to: value
            }
        )
    }

    getPilot() {
        let ret = "";
        if (this.data.pilot_name) {
            ret = this.data.pilot_name;
            if (this.data.pilot2_name) {
                ret = ret + "," + this.data.pilot2_name;
                if (this.data.pilot3_name) {
                    ret = ret + "," + this.data.pilot3_name;
                }
            }
        }
        return ret;
    }


    judgeYN(data, yes = '是', no = '否', expect = '1') {
        if (data === expect) {
            return yes
        } else {
            return no
        }
    }

    getShipType(code) {
        if (code === "1") {
            return "国内"
        } else {
            return "国际"
        }
    }


    getPurposeState(code) {
        if (code === "1") {
            return "进港"
        } else {
            return "出港"
        }
    }


    async selectStartDate() {
        try {
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: this.state.startDate
            });
            if (action !== DatePickerAndroid.dismissedAction) {
                // 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
                this.setState({
                    startDate: new Date(year, month, day),
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
        }
    }


    async selectStartTime() {
        try {
            const {action, hour, minute} = await TimePickerAndroid.open({
                hour: this.state.startHour,
                minute: this.state.startMinute,
                is24Hour: true,
            });
            if (action !== TimePickerAndroid.dismissedAction) {
                this.setState({
                    startHour: hour,
                    startMinute: minute
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open time picker', message);
        }
    }

    async selectEndTime() {
        try {
            const {action, hour, minute} = await TimePickerAndroid.open({
                hour: this.state.endHour,
                minute: this.state.endMinute,
                is24Hour: true,
            });
            if (action !== TimePickerAndroid.dismissedAction) {
                this.setState({
                    endHour: hour,
                    endMinute: minute
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open time picker', message);
        }
    }


    async selectEndDate() {
        try {
            const {action, year, month, day} = await DatePickerAndroid.open({
                date: this.state.endDate
            });
            if (action !== DatePickerAndroid.dismissedAction) {
                // 这里开始可以处理用户选好的年月日三个参数：year, month (0-11), day
                this.setState({
                    endDate: new Date(year, month, day),
                })
            }
        } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
        }
    }

    getFormatDate(date) {
        const m = moment(date);
        if (m.isValid()) {
            return m.format('YYYY-MM-DD')
        } else
            return ""
    }


    getFormatTime(hour, minute) {
        if (hour < 10) {
            if (minute < 10) {
                return "0" + String(hour) + ":" + "0" + String(minute) + ":00"
            } else {
                return "0" + String(hour) + ":" + String(minute) + ":00"
            }
        } else {
            if (minute < 10) {
                return String(hour) + ":" + "0" + String(minute) + ":00"
            } else {
                return String(hour) + ":" + String(minute) + ":00"
            }
        }
    }


}

const styles = StyleSheet.create({
    phone: {
        flex: 1,
        textDecorationLine: 'underline',
        color: '#0066FF',
    },
    card: {
        borderRadius: 10,
        borderWidth: 1,
        borderStyle: 'solid',
        borderColor: '#CCCCCC',
        flexDirection: 'column',
        backgroundColor: '#ffffff',
        marginLeft: 5,
        marginRight: 5,
        marginBottom: 10
    },
    row: {
        flexDirection: 'row',
        borderBottomWidth: 0.5,
        borderStyle: 'solid',
        borderBottomColor: '#CCCCCC',
        backgroundColor: '#ffffff',
        padding: 10,
        marginLeft: 10,
        marginRight: 10
    },
    lastRow: {
        flexDirection: 'row',
        padding: 10,
        marginLeft: 10,
        marginRight: 10,
        overflow: 'visible'
    },
    cell: {
        flex: 1,
        flexDirection: 'row'
    },
    text: {
        flex: 1
    },
    textContent: {
        flex: 1,
        color: 'black'
    }
});


export default PageQzdlrDetail;